//
//  AFNetWorkingWrapper.m
//  DotNetForApi
//
//  Created by weihong xuan on 2018/1/30.
//  Copyright © 2018年 weihong xuan. All rights reserved.
//

#import "AFNetWorkingWrapper.h"

@implementation AFNetWorkingWrapper
+ (void)startMonitorNetWorkStatus:(void (^)(AFNetworkReachabilityStatus status))block
{
    /**
     AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
     AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
     AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络,不花钱
     */
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:block];
}
+(void)sendRequestWithParam:(NSDictionary *)params method:(NSString *)method action:(NSString *)action Success:(void (^)(NSURLSessionDataTask *operation,id responseObject))success Fail:(void(^)(NSString *error))fail
{
    [AFNetWorkingWrapper startMonitorNetWorkStatus:^(AFNetworkReachabilityStatus status)
     {
         if (status==1 || status==2)
         {
             NSString * url = [NSString stringWithFormat:@"%@%@",Url_Server,action];
             
             //1.管理器
             AFHTTPSessionManager *manager= [AFHTTPSessionManager manager];
             //2.0 设置请求格式
             manager.requestSerializer.timeoutInterval=20.0;//设置超时时间
             manager.requestSerializer=[AFHTTPRequestSerializer serializer];
             manager.responseSerializer=[AFHTTPResponseSerializer serializer];
             //2.1 设置返回数据类型
             manager.responseSerializer = [AFJSONResponseSerializer serializer]; //先实例化一下
             
             manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript",@"text/plain",@"application/x-javascript", nil];
             
             if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] length]>0 && [[NSString stringWithFormat:@"%@",[[[NSUserDefaults standardUserDefaults] objectForKey:@"dream_userInfo"] objectForKey:@"uid"]] length]>0) {
                 //每次访问登录接口成功后会返回token认证码,以后每次交互时在HTTP header中添加”token”和”uid”字段
                 [manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults]  objectForKey:@"token"] forHTTPHeaderField:@"token"];
                 [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@",[[[NSUserDefaults standardUserDefaults] objectForKey:@"dream_userInfo"] objectForKey:@"uid"] ] forHTTPHeaderField:@"uid"];
             }
             if ([method isEqualToString:@"post"])
             {
                 manager.requestSerializer = [AFJSONRequestSerializer serializer];
                 [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                 
                 //3.POST请求
                 [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                     NSLog(@"请求的URL：%@",task.response.URL);
                     NSLog(@"返回结果：%@",responseObject);
                     success(task,responseObject);
                     
                 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     NSLog(@"%@",error);
                     NSLog(@"operation:%@",task.response.URL);
                     fail([NSString stringWithFormat:@"%@",error]);
                 }];
             }
             else
             {
                 //3.GET请求
                 [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                     NSLog(@"请求的URL：%@",task.response.URL);
                     NSLog(@"返回结果：%@",responseObject);
                     success(task,responseObject);
                     
                 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     NSLog(@"operation:%@",task.response.URL);
                     NSLog(@"error=>%@", error);
                     fail(@"请求失败");
                 }];
             }
         }
         else//没有网
         {
             [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
             UIAlertController*alertCL = [UIAlertController alertControllerWithTitle:@"请检查网络连接" message:@"请在系统的设置->美泰克->无线数据中开启网络" preferredStyle:UIAlertControllerStyleAlert];
             UIAlertAction*btn1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                 NSLog(@"点击了取消");
             }];
             UIAlertAction*btn2 = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                 NSString * urlString = UIApplicationOpenSettingsURLString;
                 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
                     if ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0) {
                         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
                     } else {
                         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
                     }
                 }
             }];
             [alertCL addAction:btn1];
             [alertCL addAction:btn2];
             [[AFNetWorkingWrapper topViewController] presentViewController:alertCL animated:YES completion:nil];
         }
     }];
}
+ (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [AFNetWorkingWrapper _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [AFNetWorkingWrapper _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [AFNetWorkingWrapper _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [AFNetWorkingWrapper _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}
@end
